﻿using FinancialBook.Models;
using FinancialBook.Plugins;
using FinancialBook.Service;
using MvvmCross.Platform;
using MvvmCross.Plugins.Sqlite;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace FinancialBook.Service
{
    public class Repository<T> : IRepository<T> where T : class, ITCEntity, new()
    {
        IMvxSqliteConnectionFactory _IMvxSqliteConnectionFactory;
        SQLite.SQLiteConnection dbConnection;

        public Repository()
        {
            try
            {
                //TODO: connect db
                _IMvxSqliteConnectionFactory = Mvx.Resolve<IMvxSqliteConnectionFactory>();
                IFilePath fp = Mvx.Resolve<IFilePath>();
                var dbpath = fp.DBPath();

#if DEBUG
                fp.DeleteDB(dbpath);
#endif

                dbConnection = _IMvxSqliteConnectionFactory.GetConnection(dbpath);
                dbConnection.CreateTable<Category>();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

        }

        public List<T> AllItems()
        {
            return dbConnection.Table<T>().ToList();
        }

        public void Add(T item)
        {
            try
            {
                dbConnection.Insert(item);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        public void Delete(T item)
        {
            dbConnection.Delete(item);
        }

        public void Update(T item)
        {
            dbConnection.Update(item);
        }

        public T GetItem(int id)
        {
            return dbConnection.Get<T>(id);
        }
    }
}
